﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MyUtility;
using VCC.Lib.Common;
using VCC.Lib.Helpers;
using VCC.Lib.Paging;
using VCC.Model;
using VCC.Site.Components;
using VCC.Site.Properties;
using VCC.Site.ViewModels;
namespace VCC.Site.Controllers
{
    public class AdController : Controller
    {   
        ChoVietDataContext eDataContext = new ChoVietDataContext();

        #region Index Get Ad by Category
        public ActionResult Index(string cateName, int? page)
        {
            if (page == null) page = 1;
            AdIndexModel model = new AdIndexModel();
            try
            {
                if (string.IsNullOrEmpty(cateName))
                {
                    string cateShortName = Request["dropCate"] != null ? Request["dropCate"] : string.Empty;
                    string strSubId = Request["ListSubID"] != null ? Request["ListSubID"] : "";
                    string listSubShortName = string.Empty;
                    if (!string.IsNullOrEmpty(strSubId) && strSubId != "")
                    {
                        strSubId = strSubId.Trim();
                        strSubId = strSubId.Substring(0, strSubId.Length - 1);
                        string[] listSid = strSubId.Split(',');
                        model.ListSubID = strSubId;
                        var lsubs = eDataContext.Suburbs.Where(e => listSid.Contains(e.ID.ToString())).Select(e => e.ShortName).ToList();
                        if (lsubs != null && lsubs.Count() > 0)
                        {
                            int i=0;
                            foreach (string item in lsubs) {
                                listSubShortName = i == 0 ? item : listSubShortName + "_" + item;
                                i++;
                            }            
                        }
                    }
                    string url = Settings.Default.Domain;
                    if (!string.IsNullOrEmpty(cateShortName)) url = url + "Search/" + cateShortName;
                    if (!string.IsNullOrEmpty(listSubShortName)) url = url + "/" + listSubShortName;
                    return Redirect(url);
                }
                else
                {
                    model.Category = eDataContext.Categories.Where(e => e.ShortName == cateName.ToLower()).FirstOrDefault();
                }
             if (model.Category != null)
             {
                 bool isParent = model.Category.ParentID == null ? true : false;
                 if (!string.IsNullOrEmpty(model.ListSubID))
                 {
                     model.Ads = AdManager.GetListAd(model.Category.ID, isParent, model.ListSubID.Split(','), page.Value, int.Parse(Settings.Default.BoxsizeAdSearch));
                 }
                 else
                 {
                     model.Ads = AdManager.GetListAd(model.Category.ID, isParent, page.Value, int.Parse(Settings.Default.BoxsizeAdSearch));
                 }
                 model.TotalAd = model.Ads.TotalItemCount.ToString();
             }
             else
             {
                 return RedirectToAction("Index","Home");
             }
                return View(model);
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Home");
            }
        }
        #endregion

        #region Create
        public ActionResult Create()
        {
            AdCreatModel model = new AdCreatModel();
            model.VIPTypes = Utils.StringToDictionary(Settings.Default.ListTypeAd.ToString(),",");
            model.CostTypes = eDataContext.CostTypes.ToList();

            model.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
            var tem =new BaseAuthentication();
            model.CurrentUser = tem.CurrentUser;
            HttpContext.Session["UpImageTem"] = string.Format("{0:yyyy/MM/dd}", DateTime.UtcNow).Replace("/", "\\") +"\\"+ Utils.RandomString(7) + "\\"; 
            return View(model);
        }
        #endregion

        #region HttpPost Create
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(AdCreatModel rdata)
        {
            if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
            eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
            rdata.Ad.StartDate = Request["AdStartDate"] != null && Request["AdStartDate"].ToString() != string.Empty ? Utils.ParseDateTime(Request["AdStartDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
            rdata.Ad.StartDate = rdata.Ad.StartDate.Value.AddHours(DateTime.Now.Hour).AddMinutes(DateTime.Now.Minute);
            rdata.Ad.EndDate = Request["AdEndDate"] != null && Request["AdEndDate"].ToString() != string.Empty ? Utils.ParseDateTime(Request["AdEndDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
            rdata.Ad.EndDate = rdata.Ad.EndDate.Value.AddHours(DateTime.Now.Hour).AddMinutes(DateTime.Now.Minute);
            rdata.Ad.SortDate = rdata.Ad.StartDate;
            rdata.Ad.Status = byte.Parse(AdStatus.New.GetHashCode().ToString());
            var basecaptchar = HttpContext.Session["captchastring"] != null ? HttpContext.Session["captchastring"].ToString().Trim() : string.Empty;
            try
            {
                if (rdata.CaptchaCode.Trim() == basecaptchar || string.IsNullOrEmpty(rdata.Ad.Title) || string.IsNullOrEmpty(rdata.Ad.Content))
                {
                    var temp = new BaseAuthentication();
                    if (temp.CurrentUser != null) rdata.Ad.UserID = temp.CurrentUser.ID;
                    rdata.Ad.CreatedDate = DateTime.Now;
                    rdata.Ad.ModifyDate = rdata.Ad.CreatedDate;
                    rdata.Ad.Cost = decimal.Parse(rdata.AdCost.Replace(",","").ToString());
                    rdata.Ad.MetaTitle = rdata.Ad.Title;
                    if (rdata.Ad.VIPTypeID == 5) rdata.Ad.PublishYN = true;
                    else rdata.Ad.PublishYN = false;
                    string subName = Request["AdSuburbName"];
                    string[] sName = subName.Split(',');
                    rdata.Ad.SuburbID = eDataContext.Suburbs.Where(e => e.FullName.Contains(subName) || e.Name == sName[0].Trim()).Select(e => e.ID).FirstOrDefault();
                    
                    eDataContext.Ads.InsertOnSubmit(rdata.Ad);
                    eDataContext.SubmitChanges();
                    // Upload image descriptions - gallery
                    //Check image exist
                    if (Session["UpImageTem"] != null && string.IsNullOrEmpty(Session["UpImageTem"].ToString()))
                    {
                        string[] listImageT = Utils.GetImageInFolder(Settings.Default.SiteRootPath, Settings.Default.AdImageUploadTemp + Session["UpImageTem"].ToString());

                        if (listImageT.Count() > 0)
                        {
                            string MiddlePath = string.Format("{0:yyyy/MM/dd}", rdata.Ad.CreatedDate).Replace("/", "\\");
                            MiddlePath = MiddlePath + "\\" + rdata.Ad.ID + "\\";
                            int i = 0;
                            foreach (string fFullPath in listImageT)
                            {
                                var r = new Gallery();
                                r.AdID = rdata.Ad.ID;
                                r.CreatedDate = DateTime.Now;
                                eDataContext.Galleries.InsertOnSubmit(r);
                                eDataContext.SubmitChanges();
                                string setfName = TextHelper.ToUrlFriendly(rdata.Ad.Title);
                                string xtendname = fFullPath.Split('.').LastOrDefault();
                                string fileName = setfName + "_" + rdata.Ad.ID.ToString() + "_" + r.ID.ToString() + "." + xtendname;
                                r.Path = Utils.ReduceImageSizeThenDelete(fileName, Settings.Default.AdImageDescriptionPath + MiddlePath, Settings.Default.SiteRootPath, Convert.ToInt32(Settings.Default.RedureSizePercent), fFullPath);
                                // Insert Ad Avata first image
                                if (i == 0)
                                {
                                    int adWidth = Convert.ToInt32(Settings.Default.GenThumbAdWidth.ToString());
                                    int adHeight = Convert.ToInt32(Settings.Default.GenThumbAdHeight.ToString());
                                    var img = Utils.CreateThumbnail(Settings.Default.SiteRootPath + r.Path.Replace('/', '\\'), adWidth, adHeight);
                                    rdata.Ad.AvataImage = Utils.SaveThumbnail(img, adWidth, adHeight, fileName, Settings.Default.AdImageAvatarPath + MiddlePath, Settings.Default.SiteRootPath);
                                }
                                listImageT[i] = string.Empty;
                                i++;
                            }
                        }
                    }
                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();
                    HttpContext.Session["CreatedAdSucc"] = string.Format("{0:dd/MM/yyyy}",rdata.Ad.StartDate) + ";"+rdata.Ad.NameContact +";"+rdata.Ad.MobileContact +";"+ LinkUtils.UrlAdDetails(rdata.Ad.Title, rdata.Ad.ID);
                    return Redirect(Settings.Default.Domain);
                }
                else
                {
                    ViewData[Messages.MessageTopInfo] = MessageType.Error + "Bạn đã nhập mã an toàn không chính xác. Vui lòng kiểm tra lại các thông tin của tin rao và nhập chính xác mã an toàn trước khi click Đăng Tin";
                    rdata.VIPTypes = Utils.StringToDictionary(Settings.Default.ListTypeAd.ToString(), ",");
                    rdata.CaptchaCode = string.Empty;
                    rdata.CostTypes = eDataContext.CostTypes.ToList();
                    rdata.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                    var tem = new BaseAuthentication();
                    rdata.CurrentUser = tem.CurrentUser;
                    return View(rdata);
                }
            }
            catch (Exception ex)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageTopInfo] = MessageType.Error + "Quá trình đăng tin phát sinh lỗi. Bạn vui lòng gửi thông tin và hình ảnh cho tin rao của bạn về địa chỉ email:'Support@nguoiviettaiuc.com'. Hoặc gọi điện tới số: 0474 99 2468. Chúng tôi sẽ hỗ trợ bạn đăng tin này lên website Nguoiviettaiuc.com";
                rdata.VIPTypes = Utils.StringToDictionary(Settings.Default.ListTypeAd.ToString(), ",");
                rdata.CostTypes = eDataContext.CostTypes.ToList();
                rdata.CaptchaCode = string.Empty;
                rdata.CategoryBuiltTree = CategoryManager.BuiltCombobox(0);
                var tem = new BaseAuthentication();
                rdata.CurrentUser = tem.CurrentUser;
                eDataContext.Dispose();
                ErrorLog.WriteLog(ex, Settings.Default.SiteRootPath + "LogFile");
                return View(rdata);
            }
        }
        #endregion

        #region AdDetails
        public ActionResult Details(int id)
        {
            AdDetailsModel model = new AdDetailsModel();
            try
            {
                model.Ad = eDataContext.Ads.Where(e => e.ID == id && e.PublishYN == true).FirstOrDefault();
                DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                if (model.Ad != null)
                {
                    model.AdSameCateLocation = eDataContext.Ads.Where(e => (e.CatID == model.Ad.CatID || (model.Ad.Category.ParentID != null ? e.Category.ParentID == model.Ad.Category.ParentID : false)) && e.PublishYN == true && 
                                            e.ID != id &&
                                            e.Status != byte.Parse(AdStatus.Deleted.GetHashCode().ToString()) &&
                                            e.StartDate <= today)
                                            .OrderBy(string.Format("{0} {1}", "SortDate", "DESC"))
                                            .OrderBy(string.Format("{0} {1}", "VIPTypeID", "ASC"))
                                            .ToPagedList(0, int.Parse(Settings.Default.BoxSizeAdSameCateLocation));
                    //if (model.AdSameCateLocation.Count() <= 20)
                    //{
                    //    model.IsNotEnough = true;
                    //    model.AdSameCateLocation = eDataContext.Ads.Where(e => (e.CatID == model.Ad.CatID ||( model.Ad.Category.ParentID!= null ? e.Category.ParentID == model.Ad.Category.ParentID: false)) && e.PublishYN == true && 
                    //                            e.ID != id &&
                    //                            e.Status != byte.Parse(AdStatus.Deleted.GetHashCode().ToString()) &&
                    //                            e.StartDate <= today)
                    //                            .OrderBy(string.Format("{0} {1}", "SortDate", "DESC"))
                    //                            .OrderBy(string.Format("{0} {1}", "VIPTypeID", "ASC"))
                    //                            .ToPagedList(0, int.Parse(Settings.Default.BoxSizeAdSameCateLocation));
                    //}
                    if (model.Ad.UserID != null && model.Ad.UserID > 0)
                    {
                        model.TotalAdSameUser = eDataContext.Ads.Where(e => e.UserID == model.Ad.UserID).Count();
                    }
                    model.Galleries = eDataContext.Galleries.Where(e => e.AdID == model.Ad.ID).ToList();
                    model.Tags = eDataContext.AdTagMaps.Where(e => e.AdID == model.Ad.ID).Select(e => e.Tag).ToList();
                    model.ParentCategory = model.Ad.Category.ParentCategory;
                    model.ChildenCategory = model.Ad.Category;
                    model.Suburb = model.Ad.Suburb;
                    model.Ad.ViewNumber = model.Ad.ViewNumber != null && model.Ad.ViewNumber > 0 ? model.Ad.ViewNumber + 1 : 1;
                    eDataContext.SubmitChanges();
                    return View(model);
                }
                else {
                    return Redirect(Settings.Default.Domain);
                }
            }
            catch (Exception ex)
            {
                MyLogfile.WriteLogError(ex);
                return Redirect(Settings.Default.Domain);
            }
        }    
        #endregion

        #region ChildActionOnly BoxSearchAd
        [ChildActionOnly]
        public ActionResult BoxSearchAd()
        {
            return View();
        }
        #endregion

        #region ChildActionOnly BoxQuickSearchAd
        [ChildActionOnly]
        public ActionResult BoxQuickSearchAd(int? cateID, string keywords)
        {
            BoxQuickSearchAdModel model = new BoxQuickSearchAdModel();
            if(cateID.HasValue) model.CurrentCateID = cateID.Value;
            if (!string.IsNullOrEmpty(keywords)) model.Keywords = keywords;
            model.Categories = CategoryManager.BuiltComboboxShortName(0);
            return View(model);
        }
        #endregion

        #region ChildActionOnly TabGetJob
        [ChildActionOnly]
        public ActionResult TabGetJob()
        {
            return View();
        }
        #endregion

        #region ChildActionOnly BoxAdManyView
        [ChildActionOnly]
        public ActionResult BoxAdManyView(int id, int boxsize)
        {
            BoxAdManyViewModel model = new BoxAdManyViewModel();
            model.Ads = eDataContext.Ads.Where(e => e.PublishYN == true &&
                                               (e.CatID == id || e.Category.ParentID == id) &&
                                                e.StartDate <= DateTime.Now.AddDays(-7) && e.EndDate >= DateTime.Today 
                                                && e.Status != byte.Parse(AdStatus.Deleted.GetHashCode().ToString())
                                                )
                                                .OrderBy("ViewNumber", "DESC")
                                                .ToPagedList(0, boxsize);
            if (id == 1)
            {
                model.TitleBox = Settings.Default.BoxRealManyViewTitle;
            }
            else if (id == 4) { model.TitleBox = Settings.Default.BoxJobManyViewTitle; }
            else
            {
                model.TitleBox = eDataContext.Categories.Where(e => e.ID == id).FirstOrDefault().Name.ToString();
            }
            return View(model);
        }
        #endregion

        #region ChildActionOnly PathSubMenu
        [ChildActionOnly]
        public ActionResult PathSubMenu(Category parentCate, Category childenCate, Suburb suburb)
        {
            PathSubMenuModel model = new PathSubMenuModel();
            model.ParentCategory = parentCate;
            model.ChildenCategory = childenCate;
            model.Suburb = suburb;
            return View(model);       
        }
        #endregion

        #region ChildActionOnly BoxCategoryLeft
        [ChildActionOnly]
        public ActionResult BoxCategoryLeft( int? currentCateID)
        {
            BoxCategoryLeftModel model = new BoxCategoryLeftModel();
            model.ParentCategories = eDataContext.Categories.Where(e => e.PubYN == true && e.ParentID == null).OrderBy(e => e.Priority).ToList();
            model.CurrentCateID = currentCateID != null ? currentCateID.Value : 0;
            model.Domain = Settings.Default.Domain;
            return View(model);
        }
        #endregion

        #region BoxCategoryLeft
        public ActionResult CreateAdsuccessful(Ad ad)
        {
            CreateAdsuccessfulModel model = new CreateAdsuccessfulModel();
            model.Ad = ad;
            model.Domain = Settings.Default.Domain; 
            return View(model);
        }
        #endregion

        #region ReduceImageSize
        //Reduce Image size VietLV: 20-11-2014
        public static string ReduceISize(string fileName, string path, string rootPath, int quality, HttpPostedFileBase fbfile)
        {
            try
            {
                if (fbfile != null && fbfile.ContentLength > 0)
                {
                    if (quality < 0 || quality > 100) quality = 50;

                    Stream str = fbfile.InputStream;
                    System.Drawing.Image img = System.Drawing.Image.FromStream(str);


                    // Encoder parameter for image quality 
                    EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                    // Jpeg image codec 
                    ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                    EncoderParameters encoderParams = new EncoderParameters(1);
                    encoderParams.Param[0] = qualityParam;
                    var fullpath = rootPath + path;
                    //Check exist path
                    if (!Directory.Exists(fullpath))
                        Directory.CreateDirectory(fullpath);
                    img.Save(fullpath + fileName, jpegCodec, encoderParams);
                    string pathReturn = path + fileName;
                    return pathReturn.Replace('\\', '/');
                }
                else return string.Empty;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }

        public ActionResult IUpload()
        {
            return View();
        }

        public ActionResult UploadImage(HttpPostedFileBase fb)
        {
            HttpPostedFileBase f = fb;
            return View();
        }

        public void ProcessRequest(HttpContext context)
        {
            var Request = context.Request;
            var Response = context.Response;
            var Application = context.Application;
            var Server = context.Server;

            var cmd = Request.QueryString["cmd"] ?? "";
            switch (cmd)
            {
                case "":
                    {
                        if (!((List<string>)Application["UploadKeys"]).Contains(Request.Form["k"]))
                        {
                            Response.Write("Not found");
                            return;
                        }
                        // Tạo độ trễ, bỏ comment nếu bạn chạy thử trên local 
                        // vì quá trình upload sẽ diễn ra rất nhanh
                         System.Threading.Thread.Sleep(200); 
                        var data = Request.Form["d"];
                         System.IO.File.AppendAllText(Server.MapPath("./data/") + Request.Form["k"] + ".base64", data, Encoding.ASCII);
                        Response.Write("OK");
                        return;
                    }
                case "create":
                    {
                        var key = DateTime.Now.Ticks + "";
                        Response.Write("OK " + key);
                        ((List<string>)Application["UploadKeys"]).Add(key);
                        return;
                    }
                case "close":
                    {
                        if (!((List<string>)Application["UploadKeys"]).Remove(Request.Form["k"]))
                        {
                            Response.Write("Not found");
                            return;
                        }
                        using (var fin = new FileStream(Server.MapPath("./data/") + Request.Form["k"] + ".base64", FileMode.Open))
                        {
                            var reader = new VCC.Site.Components.Base64StreamReader(fin);
                            using (var fs = new FileStream(Server.MapPath("./data/") + Request.Form["k"], FileMode.Create))
                            {
                                var buffer = new byte[1024 * 16];
                                int readLength;
                                while ((readLength = reader.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fs.Write(buffer, 0, readLength);
                                }
                                fs.Close();
                                fin.Close();
                            }
                        }
                        Response.Write("OK");
                        return;
                    }
                case "cancel":
                    {
                        if (!((List<string>)Application["UploadKeys"]).Remove(Request.Form["k"]))
                        {
                            Response.Write("Not found");
                            return;
                        }
                        System.IO.File.Delete(Server.MapPath("./data/") + Request.Form["k"] + ".base64");
                        Response.Write("OK");
                        return;
                    }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        [HttpPost]
        public void TryUpload()
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
                file.SaveAs(path);
            }
        }

    }
}
